<template>
  <div class="page-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">仪表盘</h1>
        <p class="page-description">欢迎回来，今天是 {{ currentDate }}</p>
      </div>
      <div class="header-right">
        <a-dropdown @select="handleExportSelect">
          <a-button type="outline">
            <template #icon>
              <font-awesome-icon :icon="['fas', 'download']" />
            </template>
            导出报表
            <font-awesome-icon :icon="['fas', 'angle-down']" style="margin-left: 8px;" />
          </a-button>
          <template #content>
            <a-doption value="csv">
              <template #icon>
                <font-awesome-icon :icon="['fas', 'file-csv']" />
              </template>
              导出CSV报表
            </a-doption>
            <a-doption value="json">
              <template #icon>
                <font-awesome-icon :icon="['fas', 'file-code']" />
              </template>
              导出JSON数据
            </a-doption>
          </template>
        </a-dropdown>
      </div>
    </div>
    
    <!-- 统计卡片 -->
    <a-row :gutter="24" class="stats-row">
      <a-col :span="6" v-for="stat in statsCards" :key="stat.key">
        <div class="stat-card">
          <div class="stat-icon" :class="stat.iconClass">
            <font-awesome-icon :icon="['fas', stat.icon]" />
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stat.value }}</div>
            <div class="stat-label">{{ stat.label }}</div>
            <div class="stat-trend" :class="stat.trend.type">
              <font-awesome-icon :icon="['fas', stat.trend.icon]" />
              {{ stat.trend.value }}
            </div>
          </div>
        </div>
      </a-col>
    </a-row>
    
    <!-- 图表区域 -->
    <a-row :gutter="24" class="charts-row">
      <!-- 入住趋势图 -->
      <a-col :span="16">
        <a-card title="入住趋势" class="chart-card">
          <template #extra>
            <a-radio-group v-model="trendPeriod" @change="handleTrendPeriodChange">
              <a-radio value="week">本周</a-radio>
              <a-radio value="month">本月</a-radio>
              <a-radio value="year">全年</a-radio>
            </a-radio-group>
          </template>
          <div class="chart-container">
            <v-chart
              :option="occupancyChartOption"
              :loading="dashboardStore.loading"
              style="height: 300px;"
            />
          </div>
        </a-card>
      </a-col>
      
      <!-- 房间类型分布 -->
      <a-col :span="8">
        <a-card title="房间类型分布" class="chart-card">
          <div class="chart-container">
            <v-chart
              :option="roomTypeChartOption"
              :loading="dashboardStore.loading"
              style="height: 300px;"
            />
          </div>
        </a-card>
      </a-col>
    </a-row>
    
    <!-- 数据表格区域 -->
    <a-row :gutter="24" class="tables-row">
      <!-- 最近入住 -->
      <a-col :span="12">
        <a-card title="最近入住" class="table-card">
          <template #extra>
            <a-link @click="$router.push('/guests')">查看全部</a-link>
          </template>
          <a-table
            :columns="recentCheckinsColumns"
            :data="dashboardStore.latestReservations"
            :pagination="false"
            :loading="dashboardStore.loading"
            size="small"
          >
            <template #status="{ record }">
              <a-tag :color="getStatusColor(record.status)">
                {{ getStatusText(record.status) }}
              </a-tag>
            </template>
          </a-table>
        </a-card>
      </a-col>
      
      <!-- 即将入住 -->
      <a-col :span="12">
        <a-card title="即将入住" class="table-card">
          <template #extra>
            <a-link @click="$router.push('/reservations')">查看全部</a-link>
          </template>
          <a-table
            :columns="upcomingCheckinsColumns"
            :data="dashboardStore.latestCheckins"
            :pagination="false"
            :loading="dashboardStore.loading"
            size="small"
          >
            <template #actions="{ record }">
              <a-button type="text" size="small" @click="handleCheckin(record)">
                办理入住
              </a-button>
            </template>
          </a-table>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useDashboardStore } from '@/stores/dashboard'
import { Message } from '@arco-design/web-vue'
import { library } from '@fortawesome/fontawesome-svg-core'
import { 
  faUserCheck, 
  faUserGroup, 
  faBed, 
  faMoneyBill,
  faDownload,
  faArrowUp,
  faArrowDown,
  faAngleDown,
  faFileCsv,
  faFileCode
} from '@fortawesome/free-solid-svg-icons'
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'

library.add(faUserCheck, faUserGroup, faBed, faMoneyBill, faDownload, faArrowUp, faArrowDown, faAngleDown, faFileCsv, faFileCode)

import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import VChart from 'vue-echarts'

// 注册ECharts组件
use([
  CanvasRenderer,
  LineChart,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

const dashboardStore = useDashboardStore()

// 当前日期
const currentDate = computed(() => {
  return new Date().toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    weekday: 'long'
  })
})

// 趋势图周期
const trendPeriod = ref('week')

// 统计卡片数据
const statsCards = computed(() => [
  {
    key: 'checkins',
    label: '今日入住',
    value: dashboardStore.stats.todayCheckins,
    icon: 'user-check',
    iconClass: 'checkins',
    trend: {
      type: 'up',
      icon: 'arrow-up',
      value: '+12%'
    }
  },
  {
    key: 'checkouts',
    label: '今日退房',
    value: dashboardStore.stats.todayCheckouts,
    icon: 'user-group',
    iconClass: 'checkouts',
    trend: {
      type: 'down',
      icon: 'arrow-down',
      value: '-8%'
    }
  },
  {
    key: 'available',
    label: '空房数量',
    value: dashboardStore.stats.availableRooms,
    icon: 'bed',
    iconClass: 'available',
    trend: {
      type: 'up',
      icon: 'arrow-up',
      value: '+5%'
    }
  },
  {
    key: 'revenue',
    label: '今日收入',
    value: `¥${dashboardStore.stats.todayRevenue.toLocaleString()}`,
    icon: 'money-bill',
    iconClass: 'revenue',
    trend: {
      type: 'up',
      icon: 'arrow-up',
      value: '+15%'
    }
  }
])

// 入住趋势图配置
const occupancyChartOption = computed(() => ({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
  },
  yAxis: {
    type: 'value',
    axisLabel: {
      formatter: '{value}%'
    }
  },
  series: [
    {
      name: '入住率',
      type: 'line',
      data: dashboardStore.checkinTrends.map(item => item.count),
      smooth: true,
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: 'rgba(22, 93, 255, 0.3)' },
            { offset: 1, color: 'rgba(22, 93, 255, 0.05)' }
          ]
        }
      },
      lineStyle: {
        color: '#165dff'
      },
      itemStyle: {
        color: '#165dff'
      }
    }
  ]
}))

// 房间类型分布图配置
const roomTypeChartOption = computed(() => ({
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  legend: {
    orient: 'horizontal',  // 水平排列
    bottom: '0',           // 放在底部
    left: 'center',        // 居中
    itemGap: 15,           // 图例项之间的间距
    textStyle: {
      fontSize: 12
    }
  },
  series: [
    {
      name: '房间类型',
      type: 'pie',
      radius: ['40%', '65%'],  // 调整半径，为底部图例留出空间
      center: ['50%', '45%'],  // 向上移动一点，为底部图例留出空间
      data: dashboardStore.roomDistribution,
      label: {
        show: true,
        formatter: '{d}%',   // 只显示百分比
        fontSize: 12
      },
      labelLine: {
        show: true,
        length: 10,
        length2: 10
      },
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
}))

// 最近入住表格列
// 最新预订表格列
const recentCheckinsColumns = [
  { title: '预订号', dataIndex: 'reservation_number', width: 150 },
  { title: '客人姓名', dataIndex: 'guest_name' },
  { title: '房间号', dataIndex: 'room_number' },
  { title: '入住日期', dataIndex: 'check_in' },
  { title: '状态', slotName: 'status' }
]

// 最新入住表格列
const upcomingCheckinsColumns = [
  { title: '房间号', dataIndex: 'room_number' },
  { title: '客人姓名', dataIndex: 'guest_name' },
  { title: '入住日期', dataIndex: 'check_in' },
  { title: '退房日期', dataIndex: 'check_out' },
  { title: '状态', slotName: 'status' }
]

// 获取预订/房间状态颜色
const getStatusColor = (status) => {
  const colors = {
    'confirmed': 'green',   // 已确认
    'pending': 'orange',    // 待确认
    'checked_in': 'blue',   // 已入住
    'cancelled': 'red',     // 已取消
    'occupied': 'blue',     // 占用中
    'available': 'green',   // 可用
    'reserved': 'orange',   // 已预订
    'maintenance': 'gray'   // 维护中
  }
  return colors[status] || 'gray'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    'confirmed': '已确认',
    'pending': '待确认',
    'checked_in': '已入住',
    'cancelled': '已取消',
    'occupied': '占用中',
    'available': '可用',
    'reserved': '已预订',
    'maintenance': '维护中'
  }
  return texts[status] || '未知'
}

// 处理趋势图周期变化
const handleTrendPeriodChange = (value) => {
  console.log('趋势图周期变化:', value)
  // 根据周期重新获取数据
  dashboardStore.fetchCheckinTrends(value)
}

// 处理办理入住
const handleCheckin = (record) => {
  // TODO: 实现办理入住逻辑
  console.log('办理入住:', record)
}

// 处理导出选择
const handleExportSelect = (value) => {
  if (value === 'csv') {
    handleExportReport()
  } else if (value === 'json') {
    handleExportCharts()
  }
}

// 导出完整报表（CSV格式）
const handleExportReport = () => {
  try {
    const timestamp = new Date().toLocaleDateString('zh-CN').replace(/\//g, '-')
    const filename = `仪表盘报表_${timestamp}.csv`
    
    // 构建CSV内容
    let csvContent = '\uFEFF' // UTF-8 BOM，确保Excel正确识别中文
    
    // 1. 统计数据部分
    csvContent += '=== 核心统计数据 ===\n'
    csvContent += '指标,数值,趋势\n'
    csvContent += `今日入住,${dashboardStore.stats.todayCheckins},+12%\n`
    csvContent += `今日退房,${dashboardStore.stats.todayCheckouts},-5%\n`
    csvContent += `可用房间,${dashboardStore.stats.availableRooms},稳定\n`
    csvContent += `本月营收,¥${dashboardStore.stats.monthRevenue},+28%\n`
    csvContent += '\n'
    
    // 2. 入住趋势数据
    csvContent += '=== 入住趋势数据 ===\n'
    csvContent += '日期,入住数量\n'
    dashboardStore.checkinTrends.forEach(item => {
      csvContent += `${item.date || item.name},${item.value || item.count}\n`
    })
    csvContent += '\n'
    
    // 3. 房间类型分布
    csvContent += '=== 房间类型分布 ===\n'
    csvContent += '房间类型,数量,占比\n'
    dashboardStore.roomDistribution.forEach(item => {
      const total = dashboardStore.roomDistribution.reduce((sum, i) => sum + i.value, 0)
      const percentage = total > 0 ? ((item.value / total) * 100).toFixed(1) : 0
      csvContent += `${item.name},${item.value},${percentage}%\n`
    })
    csvContent += '\n'
    
    // 4. 最近预订数据
    csvContent += '=== 最近预订 ===\n'
    csvContent += '预订号,客人姓名,房间号,入住日期,状态\n'
    dashboardStore.latestReservations.forEach(item => {
      csvContent += `${item.reservation_number || '-'},${item.guest_name || '-'},${item.room_number || '-'},${item.check_in_date || '-'},${getStatusText(item.status)}\n`
    })
    csvContent += '\n'
    
    // 5. 最新入住数据
    csvContent += '=== 最新入住 ===\n'
    csvContent += '房间号,客人姓名,入住日期,退房日期,状态\n'
    dashboardStore.latestCheckins.forEach(item => {
      csvContent += `${item.room_number || '-'},${item.guest_name || '-'},${item.check_in_date || '-'},${item.check_out_date || '-'},${getStatusText(item.status)}\n`
    })
    
    // 创建并下载文件
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = filename
    link.style.display = 'none'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(link.href)
    
    Message.success(`报表已导出：${filename}`)
    console.log('导出报表成功:', filename)
  } catch (error) {
    console.error('导出报表失败:', error)
    Message.error('导出报表失败，请重试')
  }
}

// 导出图表数据（JSON格式）
const handleExportCharts = () => {
  try {
    const timestamp = new Date().toLocaleDateString('zh-CN').replace(/\//g, '-')
    const filename = `仪表盘图表数据_${timestamp}.json`
    
    // 构建JSON数据
    const chartData = {
      exportTime: new Date().toISOString(),
      exportDate: new Date().toLocaleDateString('zh-CN'),
      stats: {
        todayCheckins: dashboardStore.stats.todayCheckins,
        todayCheckouts: dashboardStore.stats.todayCheckouts,
        availableRooms: dashboardStore.stats.availableRooms,
        monthRevenue: dashboardStore.stats.monthRevenue
      },
      checkinTrends: dashboardStore.checkinTrends.map(item => ({
        date: item.date || item.name,
        value: item.value || item.count
      })),
      roomDistribution: dashboardStore.roomDistribution.map(item => {
        const total = dashboardStore.roomDistribution.reduce((sum, i) => sum + i.value, 0)
        const percentage = total > 0 ? ((item.value / total) * 100).toFixed(1) : 0
        return {
          name: item.name,
          value: item.value,
          percentage: percentage + '%'
        }
      }),
      latestReservations: dashboardStore.latestReservations,
      latestCheckins: dashboardStore.latestCheckins
    }
    
    // 创建并下载文件
    const blob = new Blob([JSON.stringify(chartData, null, 2)], { type: 'application/json;charset=utf-8;' })
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = filename
    link.style.display = 'none'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(link.href)
    
    Message.success(`图表数据已导出：${filename}`)
    console.log('导出图表数据成功:', filename)
  } catch (error) {
    console.error('导出图表数据失败:', error)
    Message.error('导出图表数据失败，请重试')
  }
}

// 组件挂载时获取数据
onMounted(() => {
  console.log('Dashboard组件已挂载，开始加载数据')
  console.log('当前Store状态:', {
    stats: dashboardStore.stats,
    loading: dashboardStore.loading
  })
  
  dashboardStore.refreshAll().then(() => {
    console.log('Dashboard数据加载完成')
  }).catch((error) => {
    console.error('Dashboard数据加载失败:', error)
  })
})
</script>

<style scoped lang="scss">
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;

  .header-left {
    flex: 1;
  }

  .header-right {
    display: flex;
    gap: 12px;
    align-items: center;
  }
}

.stats-row {
  margin-bottom: 24px;
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 16px;

  &:hover {
    box-shadow: 0 6px 24px rgba(0, 0, 0, 0.12);
    transform: translateY(-2px);
  }
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
  flex-shrink: 0;

  &.checkins {
    background: linear-gradient(135deg, rgba(22, 93, 255, 0.1), rgba(22, 93, 255, 0.1));
    color: #165dff;
  }

  &.checkouts {
    background: linear-gradient(135deg, rgba(54, 207, 201, 0.1), rgba(54, 207, 201, 0.1));
    color: #36cfc9;
  }

  &.available {
    background: linear-gradient(135deg, rgba(0, 180, 42, 0.1), rgba(0, 180, 42, 0.1));
    color: #00b42a;
  }

  &.revenue {
    background: linear-gradient(135deg, rgba(255, 125, 0, 0.1), rgba(255, 125, 0, 0.1));
    color: #ff7d00;
  }
}

.stat-content {
  flex: 1;
  min-width: 0;
}

.stat-number {
  font-size: 28px;
  font-weight: 700;
  color: #1d2129;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #86909c;
  margin-bottom: 8px;
}

.stat-trend {
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;

  &.up {
    color: #00b42a;
  }

  &.down {
    color: #f53f3f;
  }
}

.charts-row {
  margin-bottom: 24px;
}

.chart-card {
  height: 400px;

  :deep(.arco-card-body) {
    height: calc(100% - 60px);
  }
}

.chart-container {
  height: 300px;
}

.tables-row {
  margin-bottom: 24px;
}

.table-card {
  height: 400px;

  :deep(.arco-card-body) {
    height: calc(100% - 60px);
    overflow-y: auto;
  }
}

// 响应式设计
// 大屏幕 (>1440px)
@media (min-width: 1441px) {
  .page-container {
    max-width: 1600px;
  }

  .stat-card {
    padding: 28px;
  }

  .stat-icon {
    width: 56px;
    height: 56px;
    font-size: 28px;
  }

  .stat-number {
    font-size: 32px;
  }
}

// 中等屏幕 (1024px - 1440px)
@media (max-width: 1440px) {
  .stat-card {
    padding: 20px;
  }

  .stat-icon {
    width: 44px;
    height: 44px;
    font-size: 22px;
  }

  .stat-number {
    font-size: 24px;
  }
}

// 平板 (768px - 1024px)
@media (max-width: 1024px) {
  .page-header {
    .page-title {
      font-size: 22px;
    }

    .page-description {
      font-size: 13px;
    }

    .header-right {
      :deep(.arco-btn) {
        font-size: 13px;
        padding: 6px 12px;
      }
    }
  }

  .stats-row {
    :deep(.arco-col-6) {
      flex: 0 0 50%;
      max-width: 50%;
      margin-bottom: 16px;
    }
  }

  .stat-card {
    padding: 16px;
    gap: 12px;
  }

  .stat-icon {
    width: 40px;
    height: 40px;
    font-size: 20px;
  }

  .stat-number {
    font-size: 22px;
  }

  .stat-label {
    font-size: 13px;
  }

  .charts-row {
    :deep(.arco-col-16) {
      flex: 0 0 100%;
      max-width: 100%;
      margin-bottom: 16px;
    }

    :deep(.arco-col-8) {
      flex: 0 0 100%;
      max-width: 100%;
    }
  }

  .chart-card {
    height: 350px;
  }

  .tables-row {
    :deep(.arco-col-12) {
      flex: 0 0 100%;
      max-width: 100%;
      margin-bottom: 16px;
    }
  }
}

// 手机 (<768px)
@media (max-width: 768px) {
  .page-container {
    padding: 12px !important;
  }

  .page-header {
    flex-direction: column;
    gap: 12px;
    margin-bottom: 16px;

    .page-title {
      font-size: 20px;
    }

    .page-description {
      font-size: 12px;
      margin-top: 4px;
    }

    .header-right {
      width: 100%;
      margin-top: 12px;

      :deep(.arco-btn) {
        width: 100%;
      }
    }
  }

  .stats-row {
    margin-bottom: 16px;

    :deep(.arco-col-6) {
      flex: 0 0 100%;
      max-width: 100%;
      margin-bottom: 12px;

      &:last-child {
        margin-bottom: 0;
      }
    }
  }

  .stat-card {
    padding: 14px;
    gap: 10px;
  }

  .stat-icon {
    width: 36px;
    height: 36px;
    font-size: 18px;
  }

  .stat-number {
    font-size: 20px;
  }

  .stat-label {
    font-size: 12px;
    margin-bottom: 6px;
  }

  .stat-trend {
    font-size: 11px;
  }

  .charts-row {
    margin-bottom: 16px;

    :deep(.arco-col) {
      flex: 0 0 100%;
      max-width: 100%;
      margin-bottom: 12px;

      &:last-child {
        margin-bottom: 0;
      }
    }
  }

  .chart-card {
    height: 300px;

    :deep(.arco-card-header-title) {
      font-size: 15px;
    }

    :deep(.arco-radio-group) {
      font-size: 12px;
    }
  }

  .chart-container {
    height: 220px;
  }

  .lists-row {
    :deep(.arco-col) {
      flex: 0 0 100%;
      max-width: 100%;
      margin-bottom: 12px;

      &:last-child {
        margin-bottom: 0;
      }
    }
  }

  .list-card {
    :deep(.arco-card-header-title) {
      font-size: 15px;
    }

    :deep(.arco-table-th) {
      font-size: 12px;
      padding: 8px 12px;
    }

    :deep(.arco-table-td) {
      font-size: 12px;
      padding: 8px 12px;
    }

    :deep(.arco-tag) {
      font-size: 11px;
    }
  }
}

// 小屏幕手机 (<480px)
@media (max-width: 480px) {
  .page-container {
    padding: 8px !important;
  }

  .page-header {
    margin-bottom: 12px;

    .page-title {
      font-size: 18px;
    }

    .page-description {
      font-size: 11px;
    }
  }

  .stats-row {
    margin-bottom: 12px;

    :deep(.arco-col-6) {
      margin-bottom: 10px;
    }
  }

  .stat-card {
    padding: 12px;
    gap: 8px;
  }

  .stat-icon {
    width: 32px;
    height: 32px;
    font-size: 16px;
  }

  .stat-number {
    font-size: 18px;
  }

  .stat-label {
    font-size: 11px;
  }

  .stat-trend {
    font-size: 10px;
  }

  .charts-row,
  .lists-row {
    margin-bottom: 12px;

    :deep(.arco-col) {
      margin-bottom: 10px;
    }
  }

  .chart-card {
    height: 250px;

    :deep(.arco-card-header-title) {
      font-size: 14px;
    }
  }

  .chart-container {
    height: 180px;
  }

  .list-card {
    :deep(.arco-card-header-title) {
      font-size: 14px;
    }

    :deep(.arco-table-th),
    :deep(.arco-table-td) {
      font-size: 11px;
      padding: 6px 8px;
    }

    // 隐藏某些列以适应小屏幕
    :deep(.arco-table-th:nth-child(n+4)),
    :deep(.arco-table-td:nth-child(n+4)) {
      display: none;
    }
  }
}
</style>
